package com.meeting.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.meeting.entity.Customer;
import com.meeting.entity.MediaDeviceType;
import com.meeting.entity.MeetingRoom;
import com.meeting.entity.MeetingRoomDevice;
import com.meeting.exception.BusinessException;
import com.meeting.mapper.CustomerMapper;
import com.meeting.mapper.MediaDeviceTypeMapper;
import com.meeting.mapper.MeetingRoomDeviceMapper;
import com.meeting.mapper.MeetingRoomMapper;
import com.meeting.model.dto.bookingorder.BookingRequirementRequest;
import com.meeting.model.dto.customer.CustomerModifyRequest;
import com.meeting.model.dto.customer.CustomerQueryRequest;
import com.meeting.model.dto.customer.CustomerRegisterRequest;
import com.meeting.model.enums.MeetingRoomStatusEnum;
import com.meeting.model.enums.UserStatusEnum;
import com.meeting.model.vo.MeetingRoomRecommendVO;
import com.meeting.service.CustomerService;
import com.meeting.service.MediaDeviceTypeService;
import com.meeting.service.MeetingRoomDeviceService;
import com.meeting.utils.JwtUtil;
import jakarta.annotation.Resource;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.DigestUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class CustomerServiceImpl extends ServiceImpl<CustomerMapper, Customer>
    implements CustomerService{

    /**
     * 盐值，混淆密码
     */
    public static final String SALT = "meeting";
    
    @Resource
    private MeetingRoomMapper meetingRoomMapper;
    
    @Resource
    private MeetingRoomDeviceMapper meetingRoomDeviceMapper;
    
    @Resource
    private MediaDeviceTypeMapper mediaDeviceTypeMapper;
    
    @Resource
    private MediaDeviceTypeService mediaDeviceTypeService;
    
    @Resource
    private MeetingRoomDeviceService meetingRoomDeviceService;

    @Override
    public Boolean register(CustomerRegisterRequest registerRequest) {
        // 1. 校验用户名是否已存在
        LambdaQueryWrapper<Customer> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Customer::getUsername, registerRequest.getUsername());
        Customer existCustomer = this.baseMapper.selectOne(queryWrapper);
        if (existCustomer != null) {
            throw new BusinessException(400, "用户名已存在");
        }

        // 2. 创建客户对象并设置属性
        Customer customer = new Customer();
        BeanUtils.copyProperties(registerRequest, customer);
        
        // 3. 加密密码
        String encryptPassword = DigestUtils.md5DigestAsHex((SALT + registerRequest.getPassword()).getBytes());
        customer.setPassword(encryptPassword);
        
        // 4. 设置其他默认属性
        customer.setStatus(0); // 默认状态为不可用
        customer.setCreateTime(new Date());
        customer.setUpdateTime(new Date());
        customer.setIsDeleted(0); // 默认未删除
        
        // 5. 保存到数据库
        int result = this.baseMapper.insert(customer);
        return result > 0;
    }

    @Override
    public String login(String username, String password) {
        // 1. 加密密码
        String encryptPassword = DigestUtils.md5DigestAsHex((SALT + password).getBytes());
        
        // 2. 查询用户
        LambdaQueryWrapper<Customer> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Customer::getUsername, username);
        wrapper.eq(Customer::getPassword, encryptPassword);
        Customer customer = this.baseMapper.selectOne(wrapper);
        
        // 3. 校验用户是否存在
        if (customer == null) {
            throw new BusinessException(400, "用户名或密码错误");
        }
        
        // 4. 校验用户状态
        if (customer.getStatus().equals(UserStatusEnum.FROZEN.getCode())) {
            throw new BusinessException(403, "账号被冻结，请联系管理员");
        }
        if (customer.getStatus().equals(UserStatusEnum.PENDING_REVIEW.getCode())) {
            throw new BusinessException(403, "账号审核中，请联系管理员");
        }
        if (customer.getStatus().equals(UserStatusEnum.REJECTED.getCode())) {
            throw new BusinessException(403, "账号审核拒绝，请联系管理员");
        }
        
        // 5. 生成token
        return JwtUtil.generateToken(customer);
    }
    
    @Override
    public MeetingRoomRecommendVO getMeetingRoomDetail(Long meetingRoomId) {
        // 1. 查询会议室信息
        MeetingRoom meetingRoom = meetingRoomMapper.selectById(meetingRoomId);
        if (meetingRoom == null) {
            throw new BusinessException(404, "会议室不存在");
        }
        
        // 2. 转换为VO对象
        MeetingRoomRecommendVO vo = new MeetingRoomRecommendVO();
        BeanUtils.copyProperties(meetingRoom, vo);
        
        // 3. 查询会议室设备
        List<MediaDeviceType> deviceList = getDeviceListByRoomId(meetingRoomId);
        vo.setDeviceList(deviceList);
        
        return vo;
    }

    @Override
    public Wrapper<Customer> getQueryWrapper(CustomerQueryRequest queryRequest) {
        LambdaQueryWrapper<Customer> wrapper = new LambdaQueryWrapper<>();
        if (queryRequest == null) {
            return wrapper;
        }

        Long id = queryRequest.getId();
        String username = queryRequest.getUsername();
        String realName = queryRequest.getRealName();
        String company = queryRequest.getCompany();
        String phone = queryRequest.getPhone();
        Integer status = queryRequest.getStatus();

        wrapper.eq(ObjectUtils.isNotEmpty(id), Customer::getId, id);
        wrapper.like(StringUtils.isNotBlank(username), Customer::getUsername, username);
        wrapper.like(StringUtils.isNotBlank(realName), Customer::getRealName, realName);
        wrapper.like(StringUtils.isNotBlank(company), Customer::getCompany, company);
        wrapper.like(StringUtils.isNotBlank(phone), Customer::getPhone, phone);
        wrapper.eq(ObjectUtils.isNotEmpty(status), Customer::getStatus, status);

        return wrapper;
    }

    /**
     * 修改客户状态
     * @param customerModifyRequest
     * @return
     */
    @Override
    public Boolean modifyCustomerStatus(CustomerModifyRequest customerModifyRequest) {
        Long id = customerModifyRequest.getId();
        Integer status = customerModifyRequest.getStatus();
        LambdaUpdateWrapper<Customer> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(Customer::getId, id);
        wrapper.set(Customer::getStatus, status);
        return this.update(wrapper);
    }

    /**
     * 根据会议室ID获取设备列表
     * @param roomId 会议室ID
     * @return 设备列表
     */
    private List<MediaDeviceType> getDeviceListByRoomId(Long roomId) {
        // 查询会议室设备关联
        LambdaQueryWrapper<MeetingRoomDevice> deviceWrapper = new LambdaQueryWrapper<>();
        deviceWrapper.eq(MeetingRoomDevice::getMeetingRoomId, roomId);
        List<MeetingRoomDevice> roomDevices = meetingRoomDeviceMapper.selectList(deviceWrapper);
        
        if (CollectionUtils.isEmpty(roomDevices)) {
            return new ArrayList<>();
        }
        
        // 获取设备ID列表
        List<Integer> deviceIds = roomDevices.stream()
                .map(MeetingRoomDevice::getDeviceTypeId)
                .collect(Collectors.toList());
        
        // 查询设备详情
        LambdaQueryWrapper<MediaDeviceType> mediaWrapper = new LambdaQueryWrapper<>();
        mediaWrapper.in(MediaDeviceType::getId, deviceIds);
        return mediaDeviceTypeMapper.selectList(mediaWrapper);
    }
}




